<?php


namespace app\common\model;


use app\common\lib\ZhyxMongo;
use app\common\model\search\AnswerSearch;
use MongoDB\Client;
use think\Db;
use think\db\Mongo;

class Answer extends BaseModel
{

    use AnswerSearch;

    protected $jsonAssoc = true;


    public function setAnswerAttr($value)
    {
        if (is_string($value) && !empty($value)) {
            return json_decode($value, true);
        }
        return $value;
    }

    public function getStartTimeTextAttr($value, $data)
    {
        if (isset($data["startTime"]) && !empty($data["startTime"])) {
            return date("Y-m-d H:i:s", $data["startTime"]);
        }
        return "";
    }

    public function getClassificationTextAttr($value, $data)
    {

        $arr = [
            1 => "门诊",
            2 => "住院",
            3 => "医技医辅患者"

        ];
        $classInfo = $data["questions"]["classification"];
        foreach ($classInfo as $k => &$v) {

            $v = $arr[$v];
        }
        return $classInfo;
    }

    public function getStatusTextAttr($value, $data): string
    {
        $status = [0 => "未完成", 1 => "进行中", 2 => "已完成"];
        return $status[$data["status"]];
    }

    public function getPutChanelTextAttr($value, $data): string
    {

       /* if (isset($data["putChanel"])) {
            $chanel = ['qrcode' => "二维码/PC链接", 'wechat' => "微信模板消息", 'sms' => "短信", "phone" => "电话"];
            return $chanel[$data["putChanel"]];
        }*/
        return "";
    }


    public function getEndTimeTextAttr($value, $data)
    {
        if (isset($data["endTime"])) {
            return date("Y-m-d H:i:s", $data["endTime"]);
        }
        return "";
    }

    public function getCountByStatus(string $projectId)
    {
        //$collection = (new Client("mongodb://192.168.1.205/"))->selectDatabase("tumour")->selectCollection("answer");
        $collection = (ZhyxMongo::getInstance())->setCollection("answer");
        $result = $collection->aggregate([['$match' => ['deleted_at' => 0, 'projectId' => $projectId]], ['$group' => ['_id' => '$status', 'total' => ['$sum' => 1]]], ['$project' => ['count' => '$total', '_id' => false, 'status_id' => '$_id']]]);
        $arr = [];
        foreach ($result as $k => $v) {
            if ($v["status_id"] !== "") {
                $arr[$v["status_id"]] = $v["count"];
            }
        }
        return $arr;
    }

    public function getLists()
    {
        $result = $this->mongoSearch();
        $field = ["id", "answer_no", "patient_id", "putChanel", "name", "status", "startTime", "endTime", "timeCost", "projectId"];
        return $result->field($field)->order("endTime", "desc")->paginate($this->pageLimit);

    }


}